/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: future_state_manager.h
 *
 * Purpose: implementation future state manager functional
 *
 * Developer:
 *   wen.gu , 2022-08-25
 *
 * TODO:
 *
 ***************************************************************************/

#ifndef __DOG_CORE_INTERNAL_FUTURE_STATE_MANAGER_H__
#define __DOG_CORE_INTERNAL_FUTURE_STATE_MANAGER_H__
/******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#include <exception>
#include "dog/core/error_code.h"
#include "dog/core/internal/future_shared_state.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/


/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/
namespace dog {
namespace core {
namespace internal {
/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/
template <class T, class E = ErrorCode>
class FutureStateManager { // class for managing possibly non-existent associated asynchronous state object
public:
    using FutureSharedState = FutureSharedState<T, E>;
public:
    FutureStateManager() : mSharedState(nullptr) { // construct with no associated asynchronous state object
        mGetOnlyOnce = false;
    }

    FutureStateManager(FutureSharedState* new_state, bool get_once) : mSharedState(new_state) { // construct with new_state
        mGetOnlyOnce = get_once;
    }

    FutureStateManager(const FutureStateManager& other, bool get_once = false) : mSharedState(nullptr) {
        copyFrom(other);
        mGetOnlyOnce = get_once;
    }

    FutureStateManager(FutureStateManager&& other, bool get_once = false) : mSharedState(nullptr) {
        moveFrom(other);
        mGetOnlyOnce = get_once;
    }

    ~FutureStateManager() noexcept {
        if (mSharedState) {
            mSharedState->_Release();
        }
    }
public:
    FutureStateManager& operator=(const FutureStateManager& other) {
        copyFrom(other);
        return *this;
    }

    FutureStateManager& operator=(FutureStateManager&& other) {
        moveFrom(other);
        return *this;
    }

public:
    bool valid() const noexcept {
        return mSharedState && !(mGetOnlyOnce && mSharedState->_Already_retrieved());
    }

    void wait() const { // wait for signal
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        mSharedState->_Wait();
    }

    template <class rep, class per>
    FutureStatus wait_for(const chrono::duration<rep, per>& realTime) const { // wait for duration
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        return mSharedState->_Wait_for(realTime);
    }

    template <class clock, class dur>
    FutureStatus wait_until(const chrono::time_point<clock, dur>& absTime) const { // wait until time point
#if _HAS_CXX20
        static_assert(chrono::is_clock_v<clock>, "Clock type required");
#endif // _HAS_CXX20
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        return mSharedState->_Wait_until(absTime);
    }

    T& getValue() const {
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        return mSharedState->getValue(mGetOnlyOnce);
    }

    void setValue(const T& _Val, bool _Defer) { // store a result
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        mSharedState->setValue(_Val, _Defer);
    }

    void setValue(T&& _Val, bool _Defer) { // store a result
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        mSharedState->setValue(std::forward<T>(_Val), _Defer);
    }

    void abandon() { // abandon shared state
        if (mSharedState) {
            mSharedState->_Abandon();
        }
    }

    void setException(exception_ptr _Exc, bool _Defer) { // store a result
        if (!valid()) {
            _Throw_future_error2(future_errc::no_state);
        }

        mSharedState->_Set_exception(_Exc, _Defer);
    }

    void swap(FutureStateManager& other) { // exchange with other
        std::swap(mSharedState, other.mSharedState);
    }

    FutureSharedState* ptr() const {
        return mSharedState;
    }

    void copyFrom(const FutureStateManager& other) { // copy stored associated asynchronous state object from other
        if (this != std::addressof(other)) {
            if (mSharedState) {
                mSharedState->_Release();
            }

            if (other.mSharedState) { // do the copy
                other.mSharedState->_Retain();
                mSharedState   = other.mSharedState;
                mGetOnlyOnce = other.mGetOnlyOnce;
            } else {
                mSharedState = nullptr;
            }
        }
    }

    void moveFrom(FutureStateManager& other) { // move stored associated asynchronous state object from other
        if (this != std::addressof(other)) {
            if (mSharedState) {
                mSharedState->_Release();
            }

            mSharedState        = other.mSharedState;
            other.mSharedState = nullptr;
            mGetOnlyOnce      = other.mGetOnlyOnce;
        }
    }

    bool isReady() const {
        return mSharedState && mSharedState->isReady();
    }

    bool isReadyAtThreadExit() const {
        return mSharedState && mSharedState->isReadyAtThreadExit();
    }

private:
    FutureSharedState* mSharedState;
    bool mGetOnlyOnce;
};

} /** namespace internal */
} /** namespace core */
} /** namespace dog */
#endif /** !__DOG_CORE_INTERNAL_FUTURE_STATE_MANAGER_H__ */

